<template>
    <div class="app-container">
        <!-- 搜索区域 -->
        <el-card class="search-card">
            <el-form :inline="true" :model="searchForm" class="search-form">
                <el-form-item label="站点" style="width: 300px;">
                    <el-select v-model="searchForm.siteId" placeholder="请选择站点" @change="handleSiteChange" clearable
                        style="width: 100%;">
                        <el-option v-for="item in siteList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>

                <el-form-item label="监测量" style="width: 300px;">
                    <el-select v-model="searchForm.monitorId" placeholder="请选择监测量" :disabled="!searchForm.siteId"
                        style="width: 100%;" clearable>
                        <el-option v-for="item in monitorList" :key="item.monitorId" :label="item.monitorName"
                            :value="item.monitorId" />
                    </el-select>
                </el-form-item>

                <el-form-item label="对比日期" style="width: 500px;">
                    <el-date-picker v-model="searchForm.days" type="dates" placeholder="选择对比日期" style="width: 100%;"
                        value-format="YYYY-MM-DD" :picker-options="pickerOptions" :disabled="!searchForm.monitorId" />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="handleSearch"
                        :disabled="!searchForm.days || searchForm.days.length === 0">
                        查询
                    </el-button>
                    <el-button @click="resetSearch">重置</el-button>
                    <el-button @click="handleExport" :disabled="!chartData">导出数据</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 图表区域 -->
        <el-card class="chart-card mt-2">
            <Echarts :option="chartOption" :style="{ height: '400px' }" ref="chartRef" />
        </el-card>
        <div class="site-statistics">每日统计数据</div>

        <!-- 统计数据区域 -->
        <el-card class="stats-card mt-2">
            <el-table :data="siteStatistics" border stripe>
                <el-table-column prop="day" label="日期" align="center" width="120" />
                <el-table-column label="最大值" align="center">
                    <template #default="{ row }">
                        {{ row.maxVal.toFixed(2) }} {{ getMonitorUnit(searchForm.monitorId) }}
                    </template>
                </el-table-column>
                <el-table-column label="最小值" align="center">
                    <template #default="{ row }">
                        {{ row.minVal.toFixed(2) }} {{ getMonitorUnit(searchForm.monitorId) }}
                    </template>
                </el-table-column>
                <el-table-column label="平均值" align="center">
                    <template #default="{ row }">
                        {{ row.avgVal.toFixed(2) }} {{ getMonitorUnit(searchForm.monitorId) }}
                    </template>
                </el-table-column>
                <el-table-column label="振幅" align="center">
                    <template #default="{ row }">
                        {{ row.amplitude.toFixed(2) }} {{ getMonitorUnit(searchForm.monitorId) }}
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import Echarts from '@/components/ECharts'

import {
    getSiteList,
    getMonitorListBySite,
    getMultiPeriodTrend,
    exportMultiPeriodData,
    getSiteStatistics
} from '@/api/dispatch/analyze/multi_period_curve_analysis'
const { proxy } = getCurrentInstance();

// 搜索表单数据
const searchForm = reactive({
    siteId: '',
    monitorId: '',
    days: []
})

// 数据列表
const siteList = ref([])
const monitorList = ref([])
const chartData = ref(null)
const siteStatistics = ref([])
// 加载状态
const loading = ref(false)

// 日期选择器配置
const pickerOptions = reactive({
    disabledDate(time) {
        // 最多选择7天
        return searchForm.days.length >= 7
    }
})

// 图表配置
const chartOption = computed(() => {
    if (!chartData.value) return {}

    const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452']

    return {
        title: {
            text: `多时段对比曲线`,
            left: 'left',
            textStyle: {
                fontSize: 16,
                fontWeight: 'bold'
            }
        },
        tooltip: {
            trigger: 'axis',
            formatter: function (params) {
                let result = `${params[0].axisValue}<br/>`
                params.forEach(param => {
                    result += `${param.marker} ${param.seriesName}: ${param.value} ${getMonitorUnit(searchForm.monitorId)}<br/>`
                })
                return result
            }
        },
        legend: {
            data: chartData.value.lines.map(item => item.label),
            top: 30,
            right: 50
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: 80,
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: chartData.value.xAxis
        },
        yAxis: {
            type: 'value',
            name: `数值 (${getMonitorUnit(searchForm.monitorId)})`,
            nameTextStyle: {
                padding: [0, 30, 0, 0]
            }
        },
        series: chartData.value.lines.map((line, index) => ({
            name: line.label,
            type: 'line',
            data: line.points.map(point => point.value),
            smooth: true,
            lineStyle: {
                width: 2
            },
            itemStyle: {
                color: colors[index % colors.length]
            },
            symbol: 'circle',
            symbolSize: 6
        }))
    }
})

// 获取站点名称
function getSiteName(siteId) {
    const site = siteList.value.find(item => item.id === siteId)
    return site ? site.name : ''
}

// 获取监测量名称
function getMonitorName(monitorId) {
    const monitor = monitorList.value.find(item => item.monitorId === monitorId)
    return monitor ? monitor.monitorName : ''
}

// 获取监测量单位
function getMonitorUnit(monitorId) {
    const monitor = monitorList.value.find(item => item.monitorId === monitorId)
    return monitor ? monitor.monitorUnit : ''
}

// 站点变化处理
async function handleSiteChange(siteId) {
    searchForm.monitorId = ''
    if (siteId) {
        try {
            loading.value = true
            const res = await getMonitorListBySite(siteId)
            monitorList.value = res.data || []
        } catch (error) {
            console.error('获取监测量列表失败:', error)
            ElMessage.error('获取监测量列表失败')
        } finally {
            loading.value = false
        }
    } else {
        monitorList.value = []
    }
}

// 查询处理
async function handleSearch() {
    if (!searchForm.days || searchForm.days.length === 0) {
        ElMessage.warning('请至少选择一个对比日期')
        return
    }

    try {
        loading.value = true;
        let options = {
            siteId: searchForm.siteId,
            monitorId: searchForm.monitorId,
            days: searchForm.days.join(',')
        }
        const res = await getMultiPeriodTrend(options)
        chartData.value = res.data;

        const { data } = await getSiteStatistics(options);
        siteStatistics.value = data;
        ElMessage.success('数据加载成功')
    } catch (error) {
        console.error('获取数据失败:', error)
        ElMessage.error('获取数据失败')
    } finally {
        loading.value = false
    }
}

// 重置查询
function resetSearch() {
    searchForm.siteId = ''
    searchForm.monitorId = ''
    searchForm.days = []
    siteStatistics.value = []
    chartData.value = null
}

// 导出数据
async function handleExport() {
    try {
        proxy.download("/dispatch/dispatch/duoshi/trend/export", {
            siteId: searchForm.siteId,
            monitorId: searchForm.monitorId,
            days: searchForm.days.join(',')
        }, `user_${new Date().getTime()}.xlsx`);
    } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败')
    }
}

// 初始化数据
async function initData() {
    try {
        loading.value = true
        const res = await getSiteList()
        siteList.value = res.data || []
    } catch (error) {
        console.error('获取站点列表失败:', error)
        ElMessage.error('获取站点列表失败')
    } finally {
        loading.value = false
    }
}

onMounted(() => {
    initData()
})
</script>

<style scoped>
.app-container {
    padding: 20px;
}

.search-card {
    margin-bottom: 20px;
}

.search-form {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
}

.chart-card {
    margin-bottom: 20px;
}

.chart-header {
    margin-bottom: 20px;
    text-align: center;
}

.chart-header h3 {
    margin: 0;
    font-size: 16px;
    font-weight: bold;
}

.stats-card {
    margin-bottom: 20px;
}

.stats-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.mt-2 {
    margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .search-form {
        flex-direction: column;
        align-items: stretch;
    }

    .search-form .el-form-item {
        width: 100% !important;
        margin-right: 0;
    }
}

.site-statistics {
    font-size: 20px;
    font-weight: bold;
}
</style>